﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using BskLeague.Models;
using System.Web.Security;
using BskLeague.ViewModels;
using System.IO;

namespace BskLeague.Controllers
{
    [Authorize(Roles="Chef")]
    public class MyTeamController : Controller
    {
        BskLeagueDB _db = new BskLeagueDB();
        static int dupa { get; set; }            
        //
        // GET: /MyTeam/

        public ActionResult Index()
        {
            String UserName = Membership.GetUser().UserName;
            var team = _db.Teams.SingleOrDefault(t => t.ChefPlayer.UserName == UserName);
            var season = _db.Seasons.SingleOrDefault(s => s.StatusId < 3);
            ViewBag.Team = team;

            if (season != null)
            {
                //this should also consider season
                List<Match> myMachtes = _db.Matchs.Where(m => m.Team1.TeamId == team.TeamId || m.Team2.TeamId == team.TeamId).ToList();
                return View(myMachtes);
            }
            else
            {
                List<Match> myMatches = new List<Match>();
                return View(myMatches);
            }

        }

        public ActionResult PutScore(int id)
        {
            var match = _db.Matchs.SingleOrDefault(m => m.MatchId == id);

            String UserName = Membership.GetUser().UserName;
            var team = _db.Teams.SingleOrDefault(t => t.ChefPlayer.UserName == UserName);

            if (match.Team1 == team || match.Team2 == team)
            {
                return View(match);
            }
            else
            {
                return RedirectToAction("Index");
            }
        }

        [HttpPost]
        public ActionResult PutScore(Match match)
        {
            var dbMatch = _db.Matchs.SingleOrDefault(m => m.MatchId == match.MatchId);
            dbMatch.FinalScore1 = match.FinalScore1;
            dbMatch.FinalScore2 = match.FinalScore2;

            String UserName = Membership.GetUser().UserName;
            var team = _db.Teams.SingleOrDefault(t => t.ChefPlayer.UserName == UserName);
            Communicate communicate = null;
            if (dbMatch.Team1 == team)
            {
                dbMatch.Confirmed1 = true;
                if (!dbMatch.Confirmed2)
                {
                    communicate = new Communicate
                    {
                        Sender = dbMatch.Team1.ChefPlayer.UserName,
                        Receiver = dbMatch.Team2.ChefPlayer.UserName,
                        Content = "Wprowadzono wynik meczu " + dbMatch.Team1.TeamName + " vs " + dbMatch.Team2.TeamName
                        + " (" + dbMatch.FinalScore1 + " : " + dbMatch.FinalScore2 + ")",
                        Type = 0,
                        Date = DateTime.Now
                    };
                }
                else
                {
                    //we've edited the score, so the second chef should confirm it
                    dbMatch.Confirmed2 = false;
                    communicate = new Communicate
                    {
                        Sender = dbMatch.Team1.ChefPlayer.UserName,
                        Receiver = dbMatch.Team2.ChefPlayer.UserName,
                        Content = "Wyedytowano wynik meczu " + dbMatch.Team1.TeamName + " vs " + dbMatch.Team2.TeamName
                        + " (" + dbMatch.FinalScore1 + " : " + dbMatch.FinalScore2 + ")",
                        Type = 0,
                        Date = DateTime.Now
                    };
                }

                _db.Communicates.Add(communicate);
            }
            if (dbMatch.Team2 == team)
            {
                dbMatch.Confirmed2 = true;
                if (!dbMatch.Confirmed1)
                {
                    communicate = new Communicate
                    {
                        Sender = dbMatch.Team2.ChefPlayer.UserName,
                        Receiver = dbMatch.Team1.ChefPlayer.UserName,
                        Content = "Wprowadzono wynik meczu " + dbMatch.Team1.TeamName + " vs " + dbMatch.Team2.TeamName,
                        Type = 0,
                        Date = DateTime.Now
                    };
                }
                else
                {
                    //as above
                    dbMatch.Confirmed1 = false;
                    communicate = new Communicate
                    {
                        Sender = dbMatch.Team2.ChefPlayer.UserName,
                        Receiver = dbMatch.Team1.ChefPlayer.UserName,
                        Content = "Wyedytowano wynik meczu " + dbMatch.Team1.TeamName + " vs " + dbMatch.Team2.TeamName,
                        Type = 0,
                        Date = DateTime.Now
                    };
                }

                _db.Communicates.Add(communicate);
            }



            _db.SaveChanges();

            return RedirectToAction("Index");
        }


        public ActionResult ConfirmScore(int id)
        {
            String UserName = Membership.GetUser().UserName;
            var team = _db.Teams.SingleOrDefault(t => t.ChefPlayer.UserName == UserName);

            var match = _db.Matchs.SingleOrDefault(m => m.MatchId == id);

            if (match.Team1 == team)
                match.Confirmed1 = true;
            if (match.Team2 == team)
                match.Confirmed2 = true;

            _db.SaveChanges();
            return RedirectToAction("Index");
        }

        public ActionResult Communicates()
        {
            String UserName = Membership.GetUser().UserName;

            //var communicates = _db.Communicates.ToList().FindAll(c => c.Receiver == UserName);
            var communicates = _db.Communicates.Where(c => c.Receiver == UserName).OrderByDescending(c => c.Date).ToList();

            return View(communicates);
        }

        public ActionResult EditDetails(int id)
        {
            String UserName = Membership.GetUser().UserName;
            var team = _db.Teams.SingleOrDefault(t => t.ChefPlayer.UserName == UserName);
            var season = _db.Seasons.SingleOrDefault(s => s.StatusId < 3);
            var stps = _db.SeasonTeamPlayers.Include("Player").Where(stp => stp.TeamId == team.TeamId && stp.SeasonId == season.SeasonId).ToList();
            var match = _db.Matchs.SingleOrDefault(m => m.MatchId == id);

            List<Player> players = new List<Player>();
            List<int> points = new List<int>();
            List<int> fauls = new List<int>();
            List<int> minutes = new List<int>();
            List<bool> played = new List<bool>();
            //prepare fata for detailsViewModel
            foreach (var stp in stps)
            {
                players.Add(stp.Player);
                var playersPoint = _db.Points.ToList().Find(pt => pt.Player == stp.Player && pt.Match == match);
                if (playersPoint != null)
                {
                    points.Add(playersPoint.ScoredPoints);
                }
                else
                {
                    points.Add(0);
                }

                var playersFauls = _db.Fauls.ToList().Find(fl => fl.Player == stp.Player && fl.Match == match);
                if (playersFauls != null)
                {
                    fauls.Add(playersFauls.FaulsCommited);
                }
                else
                {
                    fauls.Add(0);
                }

                var playersMinutes = _db.Minutes.ToList().Find(mn => mn.Player == stp.Player && mn.Match == match);
                if (playersMinutes != null)
                {
                    minutes.Add(playersMinutes.MinutesPlayed);
                }
                else
                {
                    minutes.Add(0);
                }

                //chech if any of the above if not null. If so -> player played in the very match
                if (playersPoint != null || playersFauls != null || playersMinutes != null)
                {
                    played.Add(true);
                }
                else
                {
                    played.Add(false);
                }

            }

            var detailsViewModel = new MyTeamEditDetailsViewModel { Match = match, Players=players, Points=points, Fauls=fauls, Minutes=minutes, Played = played};

            return View(detailsViewModel);
        }

        [HttpPost]
        public ActionResult EditDetails(MyTeamEditDetailsViewModel fromView)
        {
            var dbMatch = _db.Matchs.SingleOrDefault (m => m.MatchId == fromView.Match.MatchId);
            for (int i = 0; i < fromView.Players.Count; i++ )
            {
                var dbPlayer = _db.Players.ToList().Find(p => p.PlayerId == fromView.Players[i].PlayerId);
                var point = _db.Points.SingleOrDefault(p => p.Player.PlayerId == dbPlayer.PlayerId && p.Match.MatchId == dbMatch.MatchId);
                var faul = _db.Fauls.SingleOrDefault(f => f.Player.PlayerId == dbPlayer.PlayerId && f.Match.MatchId == dbMatch.MatchId);
                var minute = _db.Minutes.SingleOrDefault(m => m.Player.PlayerId == dbPlayer.PlayerId && m.Match.MatchId == dbMatch.MatchId);

                if (fromView.Played[i] == true)
                {
                    if (point == null)
                        _db.Points.Add(new Point { Player = dbPlayer, Match = dbMatch, ScoredPoints = fromView.Points[i] });
                    else
                        _db.Entry(point).Entity.ScoredPoints = fromView.Points[i];

                    if (faul == null)
                        _db.Fauls.Add(new Faul { Player = dbPlayer, Match = dbMatch, FaulsCommited = fromView.Fauls[i] });
                    else
                        _db.Entry(faul).Entity.FaulsCommited = fromView.Fauls[i];

                    if (minute == null)
                        _db.Minutes.Add(new Minute { Player = dbPlayer, Match = dbMatch, MinutesPlayed = fromView.Minutes[i]});
                    else
                        _db.Entry(minute).Entity.MinutesPlayed = fromView.Minutes[i];
                }
                else
                {
                    if (point != null)
                        _db.Points.Remove(point);
                    if (faul != null)
                        _db.Fauls.Remove(faul);
                    if (minute != null)
                        _db.Minutes.Remove(minute);
                }

                
            }
            _db.SaveChanges();

         
            return RedirectToAction("Index");

        }

        public ActionResult CreateCommunicate()
        {
            return View();
        }

        [HttpPost]
        public ActionResult CreateCommunicate(Communicate communicate, string RL)
        {
            string[] users = RL.Split(new char[] {';'});

            foreach (var u in users)
            {
                var com = new Communicate { Date = DateTime.Now, Receiver = u, Sender = Membership.GetUser().UserName, Content = communicate.Content };
                _db.Communicates.Add(com);
            }

            _db.SaveChanges();

            return RedirectToAction("Communicates");
        }

        public ActionResult TeamDetails()
        {
            String UserName = Membership.GetUser().UserName;
            var team = _db.Teams.SingleOrDefault(t => t.ChefPlayer.UserName == UserName);
           
            return View(team);
        }

        [HttpPost]
        public ActionResult TeamDetails(Team team, HttpPostedFileBase file)
        {
            if (file != null && file.ContentLength > 0)
            {
                // generate file name
                team.LogoFileName = team.TeamName + "Logo" +file.FileName.Substring(file.FileName.IndexOf('.'));

                // store the file inside ~/App_Data/uploads folder
                var path = Path.Combine(Server.MapPath("~/uploads"), team.LogoFileName);
                file.SaveAs(path);
            }

            var dbTeam = _db.Teams.Single(t => t.TeamId == team.TeamId);

            dbTeam.LogoFileName = team.LogoFileName;
            dbTeam.Description = team.Description;
            dbTeam.TshirtColorPrimary = team.TshirtColorPrimary;
            dbTeam.TshirtColorSecondary = team.TshirtColorSecondary;
            
            _db.SaveChanges();

            return RedirectToAction("Index");
        }

        public JsonResult GetChefs()
        {
            List<string> chefsUsers = new List<string>();
            var actualSeason = _db.Seasons.SingleOrDefault(s => s.StatusId < 3);

            if (actualSeason != null)
            {
                var teams = _db.Teams.Where(t => t.STPs.Any(stp => stp.SeasonId == actualSeason.SeasonId)).ToList();

                foreach (var t in teams)
                {
                    chefsUsers.Add(t.TeamName);
                    chefsUsers.Add(t.ChefPlayer.UserName);
                }
            }
            return Json(chefsUsers.ToArray()); 
        }

        public JsonResult GetTeam()
        {
            String UserName = Membership.GetUser().UserName;
            List<string> result = new List<string>();
            var team = _db.Teams.SingleOrDefault(t => t.ChefPlayer.UserName == UserName);
            var actualSeason = _db.Seasons.SingleOrDefault(s => s.StatusId < 3);
            if (actualSeason != null)
            {
                var players = _db.SeasonTeamPlayers
                    .Include("Player")
                    .Where(stp => stp.TeamId == team.TeamId && stp.SeasonId == actualSeason.SeasonId)
                    .Select(stp => stp.Player);

                foreach (var p in players)
                {
                    result.Add(p.PlayerName + " " + p.PlayerSurname);
                    result.Add(p.UserName);
                }
            }

            return Json(result);
        }

        public ActionResult Schedule()
        {
            String UserName = Membership.GetUser().UserName;
            var team = _db.Teams.SingleOrDefault(t => t.ChefPlayer.UserName == UserName);
            var actualSeason = _db.Seasons.SingleOrDefault(s => s.StatusId < 3);
            if (actualSeason != null)
            {
                var matches = _db.Matchs.Include("Season").Include("Team1").Include("Team2").Include("Place").
                 Where(m => (m.Team1.TeamId == team.TeamId || m.Team2.TeamId == team.TeamId) && m.Season.SeasonId == actualSeason.SeasonId)
                .OrderByDescending(m => m.Date).ToList();


                return View(matches);
            }
            else
            {
                return View(new List<Match>());
            }

        }

    }
}
